package com.youxin.chat.user.mq.consumer.message;

import com.alibaba.fastjson.JSONObject;

import com.youxin.base.MsgDto;
import com.youxin.common.constant.MsgTypeEnum;
import com.youxin.chat.user.manager.ImManager;
import com.youxin.chat.user.mapper.UserInfoMapper;
import com.youxin.chat.user.model.GroupMember;
import com.youxin.chat.user.model.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

@Component
public class JoinGroupMsgResolver implements MsgResolver {

    private Logger logger = LoggerFactory.getLogger(JoinGroupMsgResolver.class);

    @Resource
    private ImManager imManager;

    @Resource
    private UserInfoMapper userInfoMapper;



    @Override
    public Boolean supportType(String type) {
        return MsgTypeEnum.JOIN_GROUP.getType().equalsIgnoreCase(type);
    }

    @Override
    public void doResolve(MsgDto msgDto) {
        logger.info("处理加入群组通知，data={}", JSONObject.toJSONString(msgDto));
        try {
            JSONObject jsonObject = JSONObject.parseObject(msgDto.getData());
            String userNo = jsonObject.getString("applyUserNo");
            List<GroupMember> groupMembers = jsonObject.getJSONArray("members").toJavaList(GroupMember.class);
            Map<String, Object> dataMap = new HashMap<>();
            UserInfo userInfo = userInfoMapper.selectByUserNo(userNo);
            dataMap.put("operatorNickname",Optional.ofNullable(userInfo.getNickName()).orElse(""));
            List<String> targetUserIds = new ArrayList<>();
            List<String> targetUserDisplayNames = new ArrayList<>();

            for(GroupMember groupMember: groupMembers){
                targetUserIds.add(groupMember.getGroupUser());
                targetUserDisplayNames.add(Optional.ofNullable(groupMember.getGroupNickName()).orElse(""));
            }
            dataMap.put("operatorNickname",userInfo.getNickName());
            dataMap.put("targetUserIds",targetUserIds);
            dataMap.put("targetUserDisplayNames",targetUserDisplayNames);
            String msg = "添加群成员";
            imManager.sendGroupMsg("Add",imManager.getSystemNo(), Arrays.asList(groupMembers.get(0).getGroupNo()),userNo, JSONObject.toJSONString(dataMap),msg);
        } catch (Exception e) {
            logger.error("处理加入群组通知失败，data={},error={}", JSONObject.toJSONString(msgDto),e);

        }
    }
}
